package com.scpii.universal.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 线程池类
 * 
 * @author yue
 * 
 */
public class ThreadPoolService {
	private static final Logger logger = LoggerFactory
			.getLogger(ThreadPoolService.class);

	/**
	 * 默认线程池大小
	 */
	public static final int DEFAULT_POOL_SIZE = 3;

	/**
	 * 池大小
	 */
	private int poolSize = DEFAULT_POOL_SIZE;

	/**
	 * 根据给定大小创建线程池
	 */
	public ThreadPoolService(int poolSize) {
		setPoolSize(poolSize);
	}

	private ExecutorService executorService;

	/**
	 * 使用线程池中的线程来执行任务
	 */
	public void execute(Runnable task) {
		executorService.execute(task);
	}

	/**
	 * 关闭当前ExecutorService
	 * 
	 * @param timeout
	 *            以毫秒为单位的超时时间
	 */
	public void shutdown(long timeout) {
		if (executorService != null && !executorService.isShutdown()) {
			executorService.shutdownNow();
			try {
				logger.info("等待,中止现存的任务");
				if (!executorService
						.awaitTermination(timeout, TimeUnit.SECONDS)) {
					executorService.shutdownNow();

					if (!executorService.awaitTermination(timeout,
							TimeUnit.SECONDS)) {
						logger.info("线程池没有终止");
					}
				}
			} catch (InterruptedException ie) {
				executorService.shutdownNow();
				Thread.currentThread().interrupt();
			}
		}

	}

	/**
	 * 关闭当前ExecutorService，随后根据poolSize创建新的ExecutorService
	 */
	public void createExecutorService() {
		shutdown(1000);
		executorService = Executors.newFixedThreadPool(poolSize);
	}

	/**
	 * 调整线程池大小
	 * 
	 * @see #createExecutorService()
	 */
	public void setPoolSize(int poolSize) {
		this.poolSize = poolSize;
		createExecutorService();
	}

	public boolean isCompleted() {
		ThreadPoolExecutor tpool = (ThreadPoolExecutor) executorService;
		long activecount = tpool.getTaskCount() - tpool.getCompletedTaskCount();
		return activecount == 0;
	}
}
